import time

from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class jingdong_spider:
    def __init__(self):
        self.url = "https://www.jd.com"
        self.browser = None
        self.driver = "../drivers/chromedriver.exe"
        self.keyword = None
        self.data = []

    def open_browser(self):
        service = Service(executable_path=self.driver)
        self.browser = webdriver.Chrome(service=service)
        self.browser.get(url=self.url)
        # time.sleep(10)

    def input_keyword(self):
        self.keyword = input("请输入要搜索商品的名称")

    def search_goods(self):
        element = self.browser.find_element(by=By.ID, value="key")
        element.send_keys(self.keyword)
        element.send_keys(Keys.ENTER)
        time.sleep(5)

    def parse_goods(self):
        for i in range(50):
            time.sleep(0.2)
            self.browser.execute_script('window.scrollBy(0,400)')

        wait = WebDriverWait(driver=self.browser, timeout=10, poll_frequency=1)
        elements = wait.until(expected_conditions.presence_of_all_elements_located((By.CLASS_NAME, "gl-item")))
        print(len(elements))

        for element in elements:
            sku = element.get_attribute('data-sku')
            print(sku)
            link = 'https://item.jd.com/{}.html'.format(sku)
            print(link)

            price = element.find_element(by=By.CSS_SELECTOR, value='div.p-price>strong').text
            print(price)

            name = element.find_element(by=By.CSS_SELECTOR, value='div.p-name>a>em').text
            print(name)

            count = element.find_element(by=By.CSS_SELECTOR, value='div.p-commit>strong').text
            print(count)

            shop = element.find_element(by=By.CSS_SELECTOR, value='div.p-shop').text
            print(shop)

            info = []
            info.append(link)
            info.append(price)
            info.append(name)
            info.append(count)
            info.append(shop)

            self.data.append(info)

    def save_data(self):
        with open(file="jd.csv", mode="w", encoding="utf-8") as f:
            head = ["link", "price", "name", "count", "shop"]
            f.write(",".join(head))
            f.write("\n")
            for item in self.data:
                f.write(",".join(item))
                f.write("\n")

    def __del__(self):
        pass


if __name__ == '__main__':
    spider = jingdong_spider()
    spider.open_browser()
    spider.input_keyword()
    spider.search_goods()
    spider.parse_goods()
    spider.save_data()
